from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
from .groupCustomers import TotalDataConsumer
import random
from threading import Thread

#清除redis中缓存的channel_name数据
class ThreadDeleteRedisChannelName(Thread):
    def delete_keys_list(self):
        from django_redis import get_redis_connection
        from .groupCustomers import GroupChatConsumer,UserToUserConsumer
        redis_conn = get_redis_connection('redis')
        all_delete_keys = []
        for key in redis_conn.scan_iter("*{}*".format(GroupChatConsumer.KEY_LINK)):
            # 将gpu的channel_name的key 取出
            all_delete_keys.append(key)

        for key in redis_conn.scan_iter("*{}*".format(UserToUserConsumer.KEY_LINK)):
            all_delete_keys.append(key)

        if all_delete_keys:
            redis_conn.delete(*all_delete_keys)
        print(all_delete_keys)
    def run(self) -> None:
        #清空redis中缓存的channel_name
        self.delete_keys_list()

class TotalConsumerUpdateData:
    GROUP = TotalDataConsumer.GROUP
    @classmethod
    def __update(cls,data):
        channel_layer = get_channel_layer()
        async_to_sync(channel_layer.group_send)(
            cls.GROUP,
            {
                "type": "update.message",
                "data": data,
            },
        )
    @classmethod
    def user_info(cls):
        #从数据库中获取到用户数据
        user_data = []
        for i in range(10):
            dic = {
                'id':random.randint(1,99),
                'name':"zzh",
            }
            user_data.append(dic)

        cls.__update(user_data)

    @classmethod
    def alert_info(cls):
        alert_data = []
        error = ['错误{}'.format(j) for j in range(20)]
        for i in range(10):
            dic = {
                'id':random.randint(1,100),
                'msg':random.choice(error)
            }

            alert_data.append(dic)
        cls.__update(alert_data)